<template>
  <div class="bank-statement-container tech-page-container">
    <div class="page-container">
      <!-- 主要内容区域 -->
      <div class="content-wrapper">
        <!-- 搜索表单 -->
        <el-card class="tech-card search-card">
          <template #header>
            <div class="card-header-tech" style="display:flex;justify-content:space-between;align-items:center;">
              <div style="display:flex;align-items:center;gap:8px;">
                <i class="bi bi-search"></i>
                <span>查询条件</span>
              </div>
              <div>
                <el-button type="primary" @click="openUploadDialog" class="tech-button">
                  <i class="bi bi-cloud-upload"></i>
                  文件上传
                </el-button>
              </div>
            </div>
          </template>

          <el-form :model="searchForm" :inline="true" class="search-form-tech" label-width="90px" label-position="right">
            <el-row :gutter="20">
              <el-col :md="6">
                <el-form-item label="银行">
                  <el-select v-model="searchForm.bank" placeholder="全部银行" clearable>
                    <el-option label="全部银行" value="" />
                    <el-option label="工商银行" value="ICBC" />
                    <el-option label="建设银行" value="CCB" />
                    <el-option label="农业银行" value="ABC" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :md="6">
                <el-form-item label="账户名称">
                  <el-input v-model="searchForm.accountName" placeholder="本方账户名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :md="6">
                <el-form-item label="对方户名">
                  <el-input v-model="searchForm.customerName" placeholder="交易对手方" clearable />
                </el-form-item>
              </el-col>
              <el-col :md="6">
                <el-form-item label="收支类型">
                  <el-select v-model="searchForm.transFlag" placeholder="全部" clearable>
                    <el-option label="全部" value="" />
                    <el-option label="收入" value="R" />
                    <el-option label="支出" value="P" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :md="8">
                <el-form-item label="交易日期">
                  <el-date-picker
                    v-model="searchForm.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :md="8">
                <el-form-item label="摘要关键词">
                  <el-input v-model="searchForm.memo" placeholder="银行摘要" clearable />
                </el-form-item>
              </el-col>
              <el-col :md="8">
                <el-form-item label-width="0">
                  <el-button type="primary" @click="searchStatements" class="tech-button">
                    <i class="bi bi-search"></i>
                    查询
                  </el-button>
                  <el-button @click="resetSearchForm" class="tech-button">
                    <i class="bi bi-arrow-clockwise"></i>
                    重置
                  </el-button>
                  <el-button type="success" @click="exportExcel" class="tech-button">
                    <i class="bi bi-file-earmark-excel"></i>
                    导出Excel
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <!-- 流水列表 -->
        <el-card class="tech-card table-card">
          <template #header>
            <div class="card-header-tech">
              <span>银行流水列表</span>
              <el-tag type="primary" class="total-count">
                共 {{ totalCount }} 条记录
              </el-tag>
            </div>
          </template>

          <el-table :data="statementList" v-loading="loading" class="tech-table" stripe border height="600">
            <el-table-column prop="trxDate" label="交易日期" width="120" />
            <el-table-column prop="bankFullName" label="银行" width="120">
              <template #default="scope">
                {{ scope.row.bankFullName || scope.row.bank || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="accountName" label="本方账户" width="150" />
            <el-table-column prop="customerName" label="对方户名" width="150" />
            <el-table-column prop="userMemo" label="摘要" min-width="200" />
            <el-table-column prop="transFlag" label="收支" width="80" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.transFlag === 'R' ? 'success' : 'danger'">
                  {{ scope.row.transFlag === 'R' ? '收入' : '支出' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="transAmount" label="金额" width="120" align="right" />
            <el-table-column prop="balanceAmount" label="余额" width="120" align="right" />
            <el-table-column label="操作" width="80" align="center">
              <template #default="scope">
                <el-button type="danger" size="small" @click="deleteStatement(scope.row.id)" class="delete-btn">
                  <i class="bi bi-trash"></i>
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="totalCount"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              class="tech-pagination"
            />
          </div>
        </el-card>

        <!-- 文件上传弹窗 -->
        <el-dialog
          v-model="uploadDialogVisible"
          title="上传银行流水文件"
          width="600px"
          class="upload-dialog-tech"
        >
          <!-- 拖拽上传区域 -->
          <el-upload
            ref="uploadRef"
            class="upload-area-tech"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            :file-list="fileList"
            multiple
            accept=".xlsx,.xls,.csv"
          >
            <div class="upload-content">
              <i class="bi bi-cloud-upload upload-icon"></i>
              <div class="upload-text">
                <h3>拖拽文件到此处或点击选择文件</h3>
                <p>支持 Excel (.xlsx, .xls)、CSV (.csv) 格式，单个文件不超过 10MB</p>
              </div>
            </div>
          </el-upload>

          <!-- 上传结果 -->
          <div v-if="uploadResults.length > 0" class="upload-results">
            <h4>上传结果：</h4>
            <div class="result-list">
              <div
                v-for="(result, index) in uploadResults"
                :key="index"
                class="result-item"
                :class="result.success ? 'success' : 'error'"
              >
                <div class="result-info">
                  <i :class="result.success ? 'bi bi-check-circle' : 'bi bi-x-circle'"></i>
                  <span class="filename">{{ result.filename }}</span>
                  <span class="status">{{ result.message }}</span>
                </div>
                <el-tag :type="result.success ? 'success' : 'danger'">
                  {{ result.success ? '成功' : '失败' }}
                </el-tag>
              </div>
            </div>
          </div>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="closeUploadDialog">关闭</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { bankStatementApi } from '@/api'
import type { BankStatementSearchParams } from '@/api'

// 加载状态与分页
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const totalCount = ref(0)

// 上传相关
const uploadDialogVisible = ref(false)
const uploadRef = ref()
const fileList = ref<UploadUserFile[]>([])
const uploadResults = ref<Array<{
  filename: string
  success: boolean
  message: string
}>>([])

const openUploadDialog = () => {
  uploadDialogVisible.value = true
}
const closeUploadDialog = () => {
  uploadDialogVisible.value = false
}

// 搜索表单
const searchForm = reactive({
  bank: '',
  accountName: '',
  customerName: '',
  transFlag: '',
  dateRange: [] as string[],
  memo: ''
})

// 流水列表数据
const statementList = ref<any[]>([])

// 上传前验证
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isValidType = [
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-excel',
    'text/csv'
  ].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只支持 Excel 和 CSV 格式文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

 // 文件变化处理（选择即上传）
const handleFileChange = async (file: any) => {
  if (!file.raw) return

  try {
    const result = await bankStatementApi.uploadBankStatementFile(file.raw)
    uploadResults.value.push({
      filename: file.name,
      success: true,
      message: '上传成功'
    })
    // 上传成功后刷新列表并关闭弹窗
    loadStatements(currentPage.value)
    closeUploadDialog()
    ElMessage.success(`${file.name} 上传成功`)
  } catch (error) {
    uploadResults.value.push({
      filename: file.name,
      success: false,
      message: '上传失败'
    })
    ElMessage.error(`${file.name} 上传失败`)
  }
}

// 加载流水列表
const loadStatements = async (page = 1) => {
  loading.value = true
  currentPage.value = page

  try {
    const params: BankStatementSearchParams = {
      pageNo: page,
      pageSize: pageSize.value,
      bank: searchForm.bank || undefined,
      accountName: searchForm.accountName || undefined,
      customerName: searchForm.customerName || undefined,
      transFlag: searchForm.transFlag || undefined,
      userMemo: searchForm.memo || undefined
    }

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.trxDate = `${searchForm.dateRange[0]} 00:00:00,${searchForm.dateRange[1]} 23:59:59`
    }

    const data = await bankStatementApi.getBankStatementPage(params)
    statementList.value = data.list || []
    totalCount.value = data.total || 0
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('加载流水列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索流水
const searchStatements = () => {
  loadStatements(1)
}

// 重置搜索表单
const resetSearchForm = () => {
  Object.assign(searchForm, {
    bank: '',
    accountName: '',
    customerName: '',
    transFlag: '',
    dateRange: [],
    memo: ''
  })
  loadStatements(1)
}

// 导出Excel
const exportExcel = async () => {
  try {
    const params: any = {
      bank: searchForm.bank || undefined,
      accountName: searchForm.accountName || undefined,
      customerName: searchForm.customerName || undefined,
      transFlag: searchForm.transFlag || undefined,
      userMemo: searchForm.memo || undefined
    }

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.trxDate = `${searchForm.dateRange[0]} 00:00:00,${searchForm.dateRange[1]} 23:59:59`
    }

    await bankStatementApi.exportExcel(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('导出失败')
  }
}

// 删除流水
const deleteStatement = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这条流水记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await bankStatementApi.deleteBankStatement(id)
    ElMessage.success('删除成功')
    loadStatements(currentPage.value)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadStatements(1)
}
const handleCurrentChange = (val: number) => {
  loadStatements(val)
}

// 页面加载时初始化
onMounted(() => {
  loadStatements(1)
})
</script>

<style scoped>
/* 引入银行流水页面特有样式 */
@import '@/styles/bank-statement-specific.css';

/* 上传控件透明化：与外层容器一致，仅保留轻微边框便于识别 */
:deep(.upload-area-tech .el-upload-dragger) {
  background-color: transparent !important;
  border-style: dashed;
  border-color: var(--el-border-color, #dcdfe6);
  box-shadow: none;
}

:deep(.upload-area-tech .el-upload-dragger:hover) {
  background-color: transparent !important;
  border-color: var(--el-color-primary, #409eff);
}

/* 文字与图标跟随容器颜色 */
:deep(.upload-area-tech .el-upload-dragger .el-upload__text),
:deep(.upload-area-tech .el-upload-dragger .el-upload__tip) {
  color: inherit;
}

/* 组件自定义内容保持简洁可见 */
.upload-content {
  display: flex;
  align-items: center;
  gap: 12px;
  color: inherit;
}

.upload-icon {
  font-size: 32px;
  opacity: 0.85;
}

.upload-text h3,
.upload-text p {
  margin: 0;
}

/* ============================= */
/* 宇宙星辰科技风：仅作用于本页组件 */
/* ============================= */

/* 卡片：玻璃拟态 + 霓虹边框 */
.tech-card {
  background: rgba(10, 14, 25, 0.6);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  border: 1px solid rgba(99, 102, 241, 0.28);
  box-shadow:
    0 0 0 1px rgba(99, 102, 241, 0.08) inset,
    0 10px 30px rgba(2, 6, 23, 0.55);
}

.card-header-tech {
  color: #e5e7eb;
  border-bottom: 1px dashed rgba(99, 102, 241, 0.25);
}

.card-header-tech i {
  color: var(--el-color-primary, #6ea8fe);
}

/* “总条数”标签微光 */
.total-count {
  background: rgba(30, 41, 59, 0.6);
  border-color: rgba(99, 102, 241, 0.35);
  color: #c7d2fe;
}

/* 表单控件：深色主题 */
:deep(.search-form-tech .el-form-item__label) {
  color: #cbd5e1;
}

:deep(.search-form-tech .el-input__wrapper),
:deep(.search-form-tech .el-select__wrapper),
:deep(.search-form-tech .el-date-editor .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(147, 197, 253, 0.2);
  box-shadow: none;
  color: #e5e7eb;
}

:deep(.search-form-tech .el-input__wrapper:hover),
:deep(.search-form-tech .el-select__wrapper:hover),
:deep(.search-form-tech .el-date-editor .el-input__wrapper:hover) {
  border-color: rgba(147, 197, 253, 0.35);
}

:deep(.search-form-tech .el-input__inner),
:deep(.search-form-tech .el-select__selected-item),
:deep(.search-form-tech .el-date-editor .el-input__inner) {
  color: #e5e7eb;
}

:deep(.search-form-tech .el-input__inner::placeholder) {
  color: #94a3b8;
}

/* 表格：深色 + 霓虹分隔 */
:deep(.tech-table) {
  background: transparent;
  color: #e5e7eb;
}

:deep(.tech-table .el-table__header-wrapper th) {
  background: rgba(10, 14, 25, 0.82);
  color: #cbd5e1;
  border-bottom: 1px solid rgba(99, 102, 241, 0.22);
}

:deep(.tech-table .el-table__body-wrapper td) {
  background: rgba(7, 11, 22, 0.45);
  border-bottom: 1px solid rgba(99, 102, 241, 0.12);
}

:deep(.tech-table .el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: rgba(15, 23, 42, 0.48);
}

:deep(.tech-table .cell .el-tag--success) {
  --el-tag-bg-color: rgba(16, 185, 129, 0.12);
  --el-tag-text-color: #86efac;
  --el-tag-border-color: rgba(16, 185, 129, 0.3);
}

:deep(.tech-table .cell .el-tag--danger) {
  --el-tag-bg-color: rgba(239, 68, 68, 0.12);
  --el-tag-text-color: #fca5a5;
  --el-tag-border-color: rgba(239, 68, 68, 0.3);
}

/* 分页：暗色 + 主色高亮 */
:deep(.tech-pagination) {
  color: #cbd5e1;
}

:deep(.tech-pagination .btn-next),
:deep(.tech-pagination .btn-prev),
:deep(.tech-pagination .el-pagination__sizes .el-select .el-input__wrapper),
:deep(.tech-pagination .el-pagination__jump) {
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(147, 197, 253, 0.2);
  color: #e5e7eb;
}

/* 弹窗：玻璃拟态 + 边框辉光 */
:deep(.upload-dialog-tech .el-dialog) {
  background: rgba(13, 18, 34, 0.86);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border: 1px solid rgba(99, 102, 241, 0.35);
  box-shadow:
    0 0 0 1px rgba(99, 102, 241, 0.12) inset,
    0 20px 60px rgba(2, 6, 23, 0.7);
}

:deep(.upload-dialog-tech .el-dialog__header) {
  border-bottom: 1px dashed rgba(99, 102, 241, 0.25);
  color: #e5e7eb;
}

:deep(.upload-dialog-tech .el-dialog__title) {
  color: #e5e7eb;
}

/* 上传拖拽区：透明 + 霓虹虚线边框 */
:deep(.upload-area-tech .el-upload-dragger) {
  border-color: rgba(99, 102, 241, 0.45);
  color: #e5e7eb;
}

:deep(.upload-area-tech .el-upload-dragger:hover) {
  border-color: var(--el-color-primary, #6ea8fe);
  box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.25);
}

.upload-icon {
  color: var(--el-color-primary, #6ea8fe);
  text-shadow: 0 0 12px rgba(99, 102, 241, 0.35);
}

.upload-text h3 {
  color: #e5e7eb;
}

.upload-text p {
  color: #94a3b8;
}

/* 表单对齐与间距优化 */
:deep(.search-form-tech .el-form-item) {
  align-items: center;
  margin-bottom: 12px;
}
:deep(.search-form-tech .el-form-item__label) {
  line-height: 32px;
}
:deep(.search-form-tech .el-input__wrapper),
:deep(.search-form-tech .el-select__wrapper),
:deep(.search-form-tech .el-date-editor .el-input__wrapper) {
  min-height: 36px;
}

/* 弹窗与列表风格统一 */
:deep(.upload-dialog-tech .el-dialog) {
  border-radius: 10px;
}
:deep(.upload-dialog-tech .el-dialog__header) {
  padding-bottom: 12px;
  margin-right: 0;
}
:deep(.upload-dialog-tech .el-dialog__body) {
  padding-top: 16px;
  background: transparent;
}

/* 上传结果块间距 */
.upload-results {
  margin-top: 16px;
}
</style>
